package com.yhh.gateway.swagger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * 用来聚合在网关里面配置的所有路由相关服务的API文档
 */
@Component
@Primary //IOC 优先选择注入
public class SwaggerProvider implements SwaggerResourcesProvider {
    public static final String API_URL = "/v2/api-docs";

    //获取YAML 中的配置
    @Autowired
    private GatewayProperties gatewayProperties;
    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        gatewayProperties.getRoutes().forEach(routeDefinition -> {
            String idName = routeDefinition.getId();
            routeDefinition.getPredicates().forEach(predicateDefinition -> {
                if("Path".equalsIgnoreCase(predicateDefinition.getName())){
                    String path = predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0");
                    SwaggerResource swaggerResource = new SwaggerResource();
                    swaggerResource.setName(idName);
                    swaggerResource.setLocation(path.replace("/**",API_URL));
                    swaggerResource.setSwaggerVersion("2.0");
                    resources.add(swaggerResource);
                }
            });
        });
        return resources;
    }
}
